package com.lwd.util;

import com.alibaba.fastjson.JSONObject;
import com.taobao.api.internal.util.WebUtils;

import javax.servlet.http.HttpServletRequest;

public class IpUtils {

    public static String getIp(HttpServletRequest request) {
        if (request.getHeader("x-forwarded-for") == null) {
            return request.getRemoteAddr();
        } else {
            return request.getHeader("x-forwarded-for");
        }
    }

    /**
     * 通过138 获取ip的位置
     *
     * @param ip
     * @return
     */
    public static String getIpLocation(String ip) {

        try {
            String url = "http://ip.taobao.com/service/getIpInfo.php?ip=" + ip;

            String json = WebUtils.doGet(url, null);
            JSONObject result = JsonUtil.strToJson(json);
            if (result.get("code").equals(0)) {
                JSONObject ipInfo = (JSONObject) result.get("data");
                return (String) ipInfo.get("country") + ipInfo.get("region") + ipInfo.get("city") + ipInfo.get("county") + ipInfo.get("isp");
            }

        } catch (Exception e) {
        }

        return ip;
    }

}